<?php

namespace App\Http\Controllers\Game\Setting;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\Common\DatasResource;
use App\Http\Resources\Common\DataResource;
use App\Models\Game\Config\Domain;
use App\Models\Game\Config\System as Config;
use App\Services\Game\Setting\DomainService;

class DomainController extends Controller
{

    /**
     * 获取数据列表
     */
    public function getList(Request $request)
    {
        $config = Config::findByType(Config::TYPE_GAME_DOMAIN);

        list ($collection, $total) = DomainService::make()->getList($request);

        return DatasResource::make($collection)->setPaginateTotal($total)->setAttribute('domain', $config->info);
    }

    /**
     * 保存数据
     *
     * @param int $id
     */
    public function saveItem(Request $request)
    {
        $this->validate($request, [
            'id' => 'nullable|integer|min:1',
            'name' => 'required|string|max:64',
            'config.transferProxy.*' => 'required|url|max:1024',
            'config.cdnGateAddress.*' => 'required|url|max:1024',
            'config.cdnClientDomain.*' => 'required|url|max:1024',
            'config.cdnGameAddress.*.protocol' => 'required|in:ws,wss',
            'config.cdnGameAddress.*.domain' => 'required|string|max:64',
            'config.cdnGameAddress.*.port' => 'required|integer|between:1,65535',
        ]);

        $data = Domain::updateOrCreate($request->only([
            'id'
        ]), $request->only([
            'name',
            'config'
        ]));

        return new DataResource($data);
    }

    /**
     * 删除数据
     *
     * @param int $id
     */
    public function destroy(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer|min:1'
        ]);
        $id = $request->input('id');

        $data = Domain::findOrFail($id);
        $data->delete();

        return new DataResource($data);
    }

    /**
     * 更新当前使用域名
     *
     * @param int $id
     */
    public function updateConfig(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer|min:1'
        ]);
        $id = $request->input('id');

        $data = Domain::findOrFail($id);

        // 更新当前使用域名
        $config = Config::updateOrCreateByType(Config::TYPE_GAME_DOMAIN, $data->config);
        // 通知游戏端配置修改
        $config->syncGameService();

        return new DataResource($data->config);
    }
}
